#include "TcpServer.hpp"
#include <memory>

static ns_protocol::Response calculate(const ns_protocol::Request &request)
{
    ns_protocol::Response resp;
    switch (request._op)
    {
    case '+':
        resp._result = request._x + request._y;
        resp._code = 0;
        break;
    case '-':
        resp._result = request._x - request._y;
        resp._code = 0;
        break;
    case '*':
        resp._result = request._x * request._y;
        resp._code = 0;
        break;
    case '/':
        if (request._y == 0)
            return ns_protocol::Response(-1, 1);
        resp._result = request._x / request._y;
        resp._code = 0;
        break;
    case '%':
        if (request._y == 0)
            return ns_protocol::Response(-1, 2);
        resp._result = request._x % request._y;
        resp._code = 0;
        break;
    default:
        return ns_protocol::Response(-1, 3);
        break;
    }
    return resp;
}

void NetCal(ns_server::Connection *conn_ptr,std::string reqstr)
{
    std::cout << "requeststr: " << reqstr << std::endl;

    // 1.反序列化
    Request req;
    req.Deserialization(reqstr);
    // 2.业务处理 + 构建response
    Response resp =calculate(req);
    // 3.序列化+定制协议
    std::string respstr=resp.Serialization();
    EnCode(respstr);
    // 4.将要输出的数据存放到sockfd对应的outbuffer中
    conn_ptr->_out_buffer+=respstr;
    // 5.因为有数据可以响应,所以将sockfd的EPOLLOUT打开
    conn_ptr->_tcp_server_ptr->EnableReadWrite(conn_ptr,true,true);
}

int main(int argc, char *argv[], char *env[])
{
    std::unique_ptr<ns_server::TcpServer> tcp_server(new ns_server::TcpServer);

    tcp_server->Dispatch(NetCal);

    return 0;
}